const express = require('express');
const router = express.Router();
const Post = require('../models/Post');
const auth = require('../middleware/auth');
const mongoose = require('mongoose');

// 调试中间件
router.use((req, res, next) => {
  console.log('📄 Posts route:', req.method, req.url);
  next();
});

// 获取帖子列表 - 只显示待收养的帖子
router.get('/', async (req, res) => {
  try {
    const { petType, location, page = 1, limit = 10 } = req.query;
    let filter = { 
      isActive: true,
      status: { $in: ['pending', 'paid'] } // 只显示待支付和已支付的帖子
    };
    
    if (petType && petType !== '全部宠物') filter.petType = petType;
    if (location) filter.location = new RegExp(location, 'i');

    const posts = await Post.find(filter)
      .populate('author', 'username avatar phone wechat')
      .populate('fosterUser', 'username avatar') //  populate收养人信息
      .sort({ createdAt: -1 })
      .limit(parseInt(limit))
      .skip((parseInt(page) - 1) * parseInt(limit));
    
    console.log(`✅ Found ${posts.length} active posts`);
    res.json(posts);
  } catch (error) {
    console.error('❌ Get posts error:', error);
    res.status(500).json({ error: '获取帖子失败' });
  }
});

// 发布帖子
router.post('/', auth, async (req, res) => {
  try {
    console.log('📝 Create post - User:', req.userId, 'Body:', req.body);
    
    // 检查是否已经有相同的帖子
    const existingPost = await Post.findOne({
      author: req.userId,
      title: req.body.title,
      isActive: true,
      status: { $in: ['pending', 'paid', 'in_progress'] }
    });

    if (existingPost) {
      console.log('⚠️ Duplicate post detected');
      return res.status(400).json({ error: '您已经发布过相同标题的帖子' });
    }

    const post = new Post({ 
      ...req.body, 
      author: req.userId,
      status: 'pending'
    });
    
    await post.save();
    
    const populatedPost = await Post.findById(post._id)
      .populate('author', 'username avatar phone wechat');
    
    console.log('✅ Post created successfully');
    res.json(populatedPost);
  } catch (error) {
    console.error('❌ Create post error:', error);
    res.status(500).json({ error: '发布帖子失败' });
  }
});

// 申请收养（收养人调用）
router.post('/:id/apply', auth, async (req, res) => {
  try {
    const postId = req.params.id;
    console.log('🙋 Apply for foster - User:', req.userId, 'Post:', postId);
    
    const post = await Post.findById(postId);
    if (!post) {
      return res.status(404).json({ error: '帖子不存在' });
    }
    
    // 不能申请自己的帖子
    if (post.author.toString() === req.userId.toString()) {
      return res.status(400).json({ error: '不能申请自己的帖子' });
    }
    
    // 检查帖子状态
    if (post.status !== 'pending') {
      return res.status(400).json({ error: '该帖子无法申请' });
    }
    
    // 设置收养人
    post.fosterUser = req.userId;
    post.status = 'in_progress'; // 进入进行中状态
    
    await post.save();
    
    const populatedPost = await Post.findById(postId)
      .populate('author', 'username avatar phone wechat')
      .populate('fosterUser', 'username avatar');
    
    console.log('✅ Foster application submitted');
    res.json({ 
      message: '申请成功，请等待寄养人支付', 
      post: populatedPost 
    });
  } catch (error) {
    console.error('❌ Apply for foster error:', error);
    res.status(500).json({ error: '申请失败' });
  }
});

// 确认完成寄养（双方都可以确认）
router.post('/:id/complete', auth, async (req, res) => {
  try {
    const postId = req.params.id;
    console.log('✅ Complete foster - User:', req.userId, 'Post:', postId);
    
    const post = await Post.findById(postId);
    if (!post) {
      return res.status(404).json({ error: '帖子不存在' });
    }
    
    // 只有帖子的作者或收养人可以确认完成
    const isAuthor = post.author.toString() === req.userId.toString();
    const isFosterUser = post.fosterUser && post.fosterUser.toString() === req.userId.toString();
    
    if (!isAuthor && !isFosterUser) {
      return res.status(403).json({ error: '无权操作' });
    }
    
    // 检查帖子状态
    if (post.status !== 'in_progress') {
      return res.status(400).json({ error: '帖子不在进行中状态' });
    }
    
    post.status = 'completed';
    post.isActive = false;
    
    await post.save();
    
    console.log('✅ Foster completed successfully');
    res.json({ 
      message: '寄养已完成', 
      post 
    });
  } catch (error) {
    console.error('❌ Complete foster error:', error);
    res.status(500).json({ error: '确认完成失败' });
  }
});

// 获取帖子详情
router.get('/:id', async (req, res) => {
  try {
    const post = await Post.findById(req.params.id)
      .populate('author', 'username avatar phone wechat')
      .populate('fosterUser', 'username avatar');
    if (!post) {
      return res.status(404).json({ error: '帖子不存在' });
    }
    res.json(post);
  } catch (error) {
    console.error('❌ Get post detail error:', error);
    res.status(500).json({ error: '获取帖子详情失败' });
  }
});

// 获取用户帖子
router.get('/user/:userId', auth, async (req, res) => {
  try {
    console.log('📋 Get user posts - User:', req.userId);
    
    // 确保用户只能访问自己的帖子
    if (req.userId !== req.params.userId) {
      return res.status(403).json({ error: '无权访问' });
    }
    
    const posts = await Post.find({ author: req.params.userId })
      .populate('author', 'username avatar')
      .populate('fosterUser', 'username avatar')
      .sort({ createdAt: -1 });
    
    res.json(posts);
  } catch (error) {
    console.error('❌ Get user posts error:', error);
    res.status(500).json({ error: '获取用户帖子失败' });
  }
});

module.exports = router;